<?php


namespace app\api\controller;


use app\admin\model\PriceLog;
use app\admin\model\RechargeSend;
use app\admin\model\Store;
use app\api\model\Order;
use app\lib\MiniWechat;
use think\facade\Log;

class Pay
{
    public function wechatNotifyByPackagePay()
    {
        $wechat_pay_res = file_get_contents('php://input');
        Log::record([
            'wechat_pay_res' => $wechat_pay_res
        ]);
        $data = \WeChat\Contracts\Tools::xml2arr($wechat_pay_res);
        $manager = \app\admin\model\Manager::where(['mch_id'=>$data['mch_id']])->find();
        $wechat = new MiniWechat($manager['mch_id'],$manager['mch_key']);
        try {
            $data = $wechat->getNOtify();
        } catch (\Exception $e) {
            return $e->getMessage();
        }

        $resultCode = $data['result_code'] ?? '';
        $returnCode = $data['return_code'] ?? '';
        if ($resultCode == 'SUCCESS' && $returnCode == 'SUCCESS') {
            $orderNum = $data['out_trade_no'];
            $order = Order::where('wechat_order_num', $orderNum)->find();
            if (empty($order)) {
                return '订单不存在';
            }
            if ($order->is_pay == 1) {
                echo $wechat->getNotifySuccessReply();
                exit;
            }
            $order->is_pay = 1;
            $order->pay_time = date('Y-m-d H:i:s', strtotime($data['time_end']));
            $order->wechat_transaction_id = $data['transaction_id'];
            $order->pay_response_data = json_encode($data);
            $order->update_time = date('Y-m-d H:i:s');
            $order->save();
            $result = \app\api\model\UserMerchantRecharge::changeRecord($order);
            $price = $order->price + $order->send_price;
            \app\admin\model\User::where('id', $order->user_id)->inc('price', $price)->update();
            PriceLog::create([
                'user_id' =>  $order->user_id,
                'price'   => $price,
                'type'    => 1,
                'store_id'=>$order->store_id,
                'manager_id'=>$order->manager_id
            ]);

             $store = Store::find(2);
             // 赠送分钟数
             if (!empty($store) && $store->first_user_pay_type == 3 && $store->package_id == $order->pg_id) {
                 $count = RechargeSend::where([
                     'user_id' => $order->user_id,
                     'pg_id' => $store->package_id,
                 ])->count();
                 if ($count == 0) {
                     RechargeSend::create([
                         'user_id' => $order->user_id,
                         'order_id' => $order->id,
                         'send_min' => $store->send_minutes,
                         'pg_id' => $store->package_id
                     ]);
                 }
             }
            echo $wechat->getNotifySuccessReply();
        }
    }
}